package drive
import (
	"time"
	"encoding/json"
)
type Memory struct {
	Key string `json:"key"`
	Value []byte `json:"value"`
	Expire int64 `json:"expire"`
}
var MemoryList map[string]Memory=make(map[string]Memory)

func MemoryPut(key string, val []byte, expire int64){
	now:=time.Now().Unix()
	MemoryList[key]=Memory{
		Key:key,
		Value:val,
		Expire:now+expire,
	}
}
func MemoryRead(key string) []byte {
	if _, ok := MemoryList[key]; ok {
		//存在
		now:=time.Now().Unix()
		if MemoryList[key].Expire<=now{
			return nil
		}
		return MemoryList[key].Value
	}
		
	return nil
	
}
func MemoryReadList()([]Memory, int){
	var list []Memory
	for key, value := range MemoryList{
		list = append(list, Memory {key, value.Value,value.Expire})
	}
	return list,len(list)
}
func MemoryDel(key string){
	delete(MemoryList,key)
}
func MemoryExpire() error {
	for key, value := range MemoryList{
		now:=time.Now().Unix()
		if value.Expire<=now{
			delete(MemoryList,key)
		}
	}
	return nil
}
func MemoryRepeat() error {
	list:=make(map[int]Memory)
	for key, value := range MemoryList{
		t := Token{}
		json.Unmarshal(value.Value, &t)
		if v2, ok := list[t.Id]; ok {
			if value.Expire>list[t.Id].Expire{
				delete(MemoryList,v2.Key)
				list[t.Id]=value
				
			}else{
				delete(MemoryList,key)
			}
		}else{
			list[t.Id]=value
		}
		
	}
	return nil
}